import crypto from 'crypto';

const cryptoPassword = 'fuckthehackers'

/**
 * 加密字符串
 * @param str
 * @returns {Buffer | string}
 */
export function encrypt(str: String) {
    const cipher = crypto.createCipher('aes192', cryptoPassword);
    let encrypted = cipher.update(str, 'utf8', 'hex');
    encrypted += cipher.final('hex');
    return encrypted;
}

/**
 * 解密字符串
 * @param encryptedStr
 * @returns {Buffer | string}
 */
export function decrypt(encryptedStr: String) {
    const decipher = crypto.createDecipher('aes192', cryptoPassword);
    let decrypted = decipher.update(encryptedStr, 'hex', 'utf8');
    decrypted += decipher.final('utf8');
    return decrypted;
}

/**
 * 生成token
 * @param user
 * @param {Number} expire - 失效时间
 */
export function createAuthToken(user: Object, expire: Number): String {
    return encrypt(`${JSON.stringify(user)}^${new Date().valueOf() + expire}`)
}

/**
 * 解析token
 * @param token
 * @returns {Buffer|string}
 */
export function parseAuthToken(token: String): Object {
    let decryptToken = decrypt(token);
    if (decryptToken.indexOf('^') >= 0) {
        const curDate = new Date().valueOf();
        const tokenDate = decryptToken.split('^')[1] || 0;
        // token失效
        if (tokenDate < curDate) {
            return null;
        }
        return JSON.parse(decryptToken.split('^')[0])
    }
    return null;
}